﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using iSun.Entity;
using iSun.Model;
using iSun.BLL.Base;
using System.Data;

namespace iSun.SYS.Bussiness.Message
{
    public partial class BDatMessageQueue : BLL.Base.BaseBussnies<DatMessageQueue>
    {
        public BDatMessageQueue() { this.entity = new DatMessageQueue(); }

        /// <summary>
        /// 设置消息为已推送
        /// </summary>
        /// <param name="messageId">消息Id</param>
        /// <returns>影响记录条数</returns>
        public int setPushState(Guid messageId)
        {

            try
            {
                string sql = "update  DatMessageQueue  set PushState='1',PushTime=getdate() where MsgID='" + messageId.ToString() + "'";
                return this.RunSqlCommand(sql);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 修改预计发送时间
        /// </summary>
        /// <param name="messageId">消息Id</param>
        /// <param name="ExpectTime">预计发送时间</param>
        /// <returns>1：修改成功；0：消息已经发送不能修改</returns>
        public int UpdateExpectTime(Guid messageId,DateTime ExpectTime ) 
        {
            int i = 0;
            try
            {
                if (!IsPushMessage(messageId))
                {
                    string sql = "update  DatMessageQueue  set ExpectTime='" + ExpectTime.ToString("yyyy-MM-dd HH:mm:ss") + "' where MsgID='" + messageId.ToString() + "' and PushState='0'";
                     i=this.RunSqlCommand(sql);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return i;
        
        }
        /// <summary>
        /// 信息是否已推送
        /// </summary>
        /// <param name="MsgID">信息编号</param>
        /// <returns></returns>
        public bool IsPushMessage(Guid MsgID) 
        {
            bool pushState = false;
            try
            {
                string s = "MsgID='"+MsgID.ToString()+"'";
                DatMessageQueue mq = this.GetEntityByCondition<DatMessageQueue>(s);
                if (mq != null) 
                {
                    if (mq.PushState == "1") { pushState = true; }
                    else { pushState = false; }
                }
            }
            catch (Exception ex)
            {

                throw ex;
            }
            return pushState;
        }
        /// <summary>
        /// 获取要发送的系统信息
        /// </summary>
        /// <returns>数据集</returns>
        public  IList<DatMessageQueue> GetSysMessages()
        {
            try
            {
                 string s = "MessageType='0' order by AddTime";
                 return this.GetEntityListByCondition<DatMessageQueue>(s);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 获取要发送Mail信息
        /// </summary>
        /// <returns>数据集</returns>
        public  IList<DatMessageQueue> GetMailMessages()
        {
            try
            {
                 string s = "MessageType='1' order by AddTime";
                 return this.GetEntityListByCondition<DatMessageQueue>(s);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 获取要发送手机短信息
        /// </summary>
        /// <returns>数据集</returns>
        public  IList<DatMessageQueue> GetSMSMessages()
        {
            try
            {
                 string s = "MessageType='2' order by AddTime";
                 return this.GetEntityListByCondition<DatMessageQueue>(s);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 获取要发送QQ信息
        /// </summary>
        /// <returns>数据集</returns>
        public IList<DatMessageQueue> GetQQMessages()
        {
            try
            {
                 string s = "MessageType='3' order by AddTime";
                 return this.GetEntityListByCondition<DatMessageQueue>(s);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }


        public IList<DatMessageQueue> GetCurrentPushMessages(DateTime CurrentTime)
        {
            try
            {
                string s = "DATEDIFF(second, ExpectTime, '" + CurrentTime + "')>=0 and  PushState='0'";
                return this.GetEntityListByCondition<DatMessageQueue>(s);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 新建消息
        /// </summary>
        /// <param name="messages">消息</param>
        /// <param name="MessageReceiver">消息接收者集体</param>
        public void AddMessage(DatMessageQueue messages, IList<DatMessageReceiver> MessageReceiver)
        {
            try
            {
                if (messages != null)
                {
                    messages.PushState = "0";
                    messages.AddTime = DateTime.Now;
                    messages.PushTime = DateTime.Now;
                    if (MessageReceiver.Count > 0)
                    {
                        messages.BaseEntityState = WorkState.New;
                        messages.SaveEntity();
                        foreach (DatMessageReceiver item in MessageReceiver)
                        {
                            item.BaseEntityState = WorkState.New;
                            item.SaveEntity();
                        }

                    }
                }
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }

        /// <summary>
        /// 推送比指定时间早的预定信息
        /// </summary>
        /// <param name="CurrentTime">当前指时间</param>
        public string PushMessages(DateTime CurrentTime)
        {
            string msgConde = "0";
            try
            {
                if (CurrentTime != null && CurrentTime != default(DateTime))
                {
                    IList<DatMessageQueue> list = GetCurrentPushMessages(CurrentTime);

                    if (list!=null&&list.Count > 0)
                    {
                        foreach (DatMessageQueue mq in list)
                        {
                            //消息体写入历史表
                            if (!new BV_HistoryMessagePool().HistoryMsgExists(mq.MsgID))
                            {
                                DatHistoryMessageQueue hMQ = new DatHistoryMessageQueue();
                                hMQ.MsgID = mq.MsgID;
                                hMQ.Title = mq.Title;
                                hMQ.MsgTemplate = mq.MsgTemplate;
                                hMQ.MsgContent = mq.MsgContent;
                                hMQ.MessageType = mq.MessageType;
                                hMQ.ExpectTime = mq.ExpectTime;
                                hMQ.AddUser = mq.AddUser;
                                hMQ.QueryID = mq.QueryID;
                                hMQ.PushState = mq.PushState;
                                hMQ.AddTime = mq.AddTime;
                                hMQ.PushTime = mq.PushTime;

                                hMQ.BaseEntityState = WorkState.New;
                                hMQ.SaveEntity();
                            }

                            PushReceivers(mq.MsgID);
                            msgConde = "1";
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                msgConde=ex.Message;
            }
            return msgConde;
        }

        [Serializable()]
        public class Criteria
        {
            private Guid _userid;
            public Guid userid
            {
                get { return _userid; }
                set { _userid = value; }
            }
        }

        /// <summary>
        /// 推送指定信息
        /// </summary>
        /// <param name="messageId"></param>
        public void PushReceivers(Guid messageId) 
        {
            try
            {
                if (messageId != null)
                {
                    IList<DatMessageReceiver> Receivers = new BDatMessageReceiver().GetReceivers(messageId);
                    if (Receivers != null && Receivers.Count > 0)
                    {
                        DatMessagePool mp = null;
                        DatHistoryMessagePool Hmp = DatHistoryMessagePool.New();
                        BMessageItem Bm = new BMessageItem();
                        IList<Criteria> list = null;
                        foreach (DatMessageReceiver mr in Receivers)
                        {
                            string recType = mr.ReceiverType;
                            switch (recType)
                            {
                                case "U":
                                    if (!Bm.MsgExists(mr.MsgID, mr.ReceiverID))
                                    {
                                        mp = DatMessagePool.New();
                                        mp.MPoolID = Guid.NewGuid();
                                        mp.MsgID = mr.MsgID;
                                        mp.ReceiverID = mr.ReceiverID;
                                        mp.SendState = "0";
                                        mp.SendTime = DateTime.Now;
                                        mp.BaseEntityState = WorkState.New;
                                        mp.SaveEntity();

                                        //Hmp = DatHistoryMessagePool.New();
                                        //Hmp.MPoolID = mp.MPoolID;
                                        //Hmp.MsgID = mp.MsgID;
                                        //Hmp.ReceiverID = mp.ReceiverID;
                                        //Hmp.SendState = mp.SendState;
                                        //Hmp.SendTime = mp.SendTime;
                                        //Hmp.BaseEntityState = WorkState.New;
                                        //Hmp.SaveEntity();
                                    }
                                    break;
                                case "D":
                                    list = GetOrgAndUser(mr.ReceiverID);
                                    if (list.Count > 0)
                                    {
                                        foreach (Criteria item in list)
                                        {
                                            if (!Bm.MsgExists(mr.MsgID, item.userid))
                                            {
                                                mp = DatMessagePool.New();
                                                mp.MPoolID = Guid.NewGuid();
                                                mp.MsgID = mr.MsgID;
                                                mp.ReceiverID = item.userid;
                                                mp.SendState = "0";
                                                mp.SendTime = DateTime.Now;
                                                mp.BaseEntityState = WorkState.New;
                                                mp.SaveEntity();

                                                //Hmp = DatHistoryMessagePool.New();
                                                //Hmp.MPoolID = mp.MPoolID;
                                                //Hmp.MsgID = mp.MsgID;
                                                //Hmp.ReceiverID = mp.ReceiverID;
                                                //Hmp.SendState = mp.SendState;
                                                //Hmp.SendTime = mp.SendTime;
                                                //Hmp.BaseEntityState = WorkState.New;
                                                //Hmp.SaveEntity();
                                            }
                                        }
                                    }
                                    break;
                                case "C":
                                    list = GetOrgAndUser(mr.ReceiverID);
                                    if (list.Count > 0)
                                    {
                                        foreach (Criteria item in list)
                                        {
                                            if (!Bm.MsgExists(mr.MsgID, item.userid))
                                            {
                                                mp = DatMessagePool.New();
                                                mp.MPoolID = Guid.NewGuid();
                                                mp.MsgID = mr.MsgID;
                                                mp.ReceiverID = item.userid;
                                                mp.SendState = "0";
                                                mp.SendTime = DateTime.Now;
                                                mp.BaseEntityState = WorkState.New;
                                                mp.SaveEntity();

                                                //Hmp = DatHistoryMessagePool.New();
                                                //Hmp.MPoolID = mp.MPoolID;
                                                //Hmp.MsgID = mp.MsgID;
                                                //Hmp.ReceiverID = mp.ReceiverID;
                                                //Hmp.SendState = mp.SendState;
                                                //Hmp.SendTime = mp.SendTime;
                                                //Hmp.BaseEntityState = WorkState.New;
                                                //Hmp.SaveEntity();
                                            }
                                        }
                                    }
                                    break;

                            }
                        }
                        setPushState(messageId);//更新状态
                    }

                    //**********************
                  
                }

            }
            catch (Exception ex)
            {

                throw ex;
            }
        }
        /// <summary>
        /// 获取指定组织架构节点的人员集合
        /// </summary>
        /// <param name="messageId"></param>
        /// <returns></returns>
        public IList<Criteria> GetOrgAndUser(Guid messageId) 
        {
         
                BaseBussnies instance = new BaseBussnies();
                string strSql = string.Format("Exec [dbo].[sp_GetOrganizeUserByNodeID] '{0}'", messageId.ToString());
                return instance.GetEntitysBySqlComm<Criteria>(strSql);
       
        }
         
        /// <summary>
        /// 
        /// </summary>
        /// <param name="instance"></param>
        /// <returns></returns>
        public override string CheckData(BaseEntity instance)
        {
            DatMessageQueue entity = instance as DatMessageQueue;
            if (string.IsNullOrEmpty(entity.Title))
            {
                return "信息标题不能为空!";
            }
            if (string.IsNullOrEmpty(entity.MsgContent))
            {
                return "信息内容不能为空!";
            }
           
            if (entity.ExpectTime!=default(DateTime))
            {
                return "预计推送时间不能为空!";
            }

            return base.CheckData(entity);
        }

        public override string CheckData()
        {
            return CheckData(this.entity);
        }

    

    }
}
